<?php

namespace frontend\modules\address\models;

use Yii;

/**
 * This is the model class for table "ecs_region".
 *
 * @property integer $region_id
 * @property integer $parent_id
 * @property string $region_name
 * @property integer $region_type
 * @property integer $agency_id
 */
class EcsRegion extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'ecs_region';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['parent_id', 'region_type', 'agency_id'], 'integer'],
            [['region_name'], 'string', 'max' => 120],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'region_id' => 'Region ID',
            'parent_id' => 'Parent ID',
            'region_name' => 'Region Name',
            'region_type' => 'Region Type',
            'agency_id' => 'Agency ID',
        ];
    }

    /**
     * @inheritdoc
     * @return \frontend\modules\address\models\query\EcsRegionQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \frontend\modules\address\models\query\EcsRegionQuery(get_called_class());
    }

    /**
     * 无限极分类
     *
     * @return array
     */
    public function getJsonAll()
    {
        $row = EcsRegion::find()->asArray()->all();
        $addrArr = array();
        foreach($row as $key=>$val){
            $addrArr[$key]['value'] = $val['region_id'];
            $addrArr[$key]['text'] = $val['region_name'];
            $addrArr[$key]['lev'] = $val['region_type'];
            $addrArr[$key]['parent_id'] = $val['parent_id'];
        }
        $addrArr = $this->make_tree($addrArr);
        return $addrArr;
    }


    /**
     * 把返回的数据集转换成Tree
     *
     * @param array $list 要转换的数据集
     * @param string $pk 自增字段（栏目id）
     * @param string $pid parent标记字段
     * @return array
     * @author dqs <1696232133@qq.com>
     */
    public function make_tree($row,$pk='value',$pid='parent_id',$child='children',$root=1){
        $tree=array();
        $packData=array();
        foreach ($row as  $data) {
            $packData[$data[$pk]] = $data;
        }
        foreach ($packData as $key =>$val){
            if($val[$pid]==$root){//代表跟节点
                $tree[]=& $packData[$key];
            }else{
                //找到其父类
                $packData[$val[$pid]][$child][]=& $packData[$key];
            }
        }
        return $tree;
    }
}
